package com.resou.reader.choosegender;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.resou.reader.MainActivity;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.GenderCategory;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.choosegender.giftbook.GiftBooksActivity;
import com.resou.reader.reader.m.SimpleAnimatorListener;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.ToastUtil;

import java.util.List;

import butterknife.BindView;

/**
 *
 */
public class ChooseGenderActivity extends ResouBaseActivity<ChooseGenderPresenter> implements View.OnClickListener, ChooseContract.View {
    int screenHeight = ReSouApplication.SCREEN_HEIGHT;
    int screenWidth = ReSouApplication.SCREEN_WIDTH;
    private static final String TAG = "ChooseActivity-App";

    @BindView(R.id.tv_you_are_here)
    TextView tvYouAreHere;
    @BindView(R.id.tv_choose_sex)
    TextView tvChooseSex;
    @BindView(R.id.ll_boy_container)
    LinearLayout llBoyContainer;
    @BindView(R.id.ll_girl_container)
    LinearLayout llGirlContainer;
    @BindView(R.id.tv_surprise)
    TextView tvSurprise;
    @BindView(R.id.tvINfo)
    TextView tvINfo;
    @BindView(R.id.tv_skip)
    TextView tvSkip;

    @BindView(R.id.ll_boy_and_girl)
    LinearLayout llBoyAndGirl;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_determine)
    TextView tvDetermine;
    @BindView(R.id.rl_clear_container)
    RelativeLayout rlClearContainer;
    @BindView(R.id.ll_recycler_container)
    LinearLayout llRecyclerContainer;
    @BindView(R.id.iv_boy)
    ImageView ivBoy;
    @BindView(R.id.tv_boy)
    TextView tvBoy;
    @BindView(R.id.iv_girl)
    ImageView ivGirl;
    @BindView(R.id.tv_girl)
    TextView tvGirl;
    @BindView(R.id.tv_clear)
    TextView tvClear;
    private float dp84;
    private float dp160;
    private float dp40;
    private float dp100;
    private ChooseBooksAdapter mAdapter;
    private String mGender;
    private boolean isAddBook = true;

    public static void start(Context context) {
        Intent starter = new Intent(context, ChooseGenderActivity.class);
//    starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void initStatusBar() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    protected void initPresenter() {
        mPresenter = new ChooseGenderPresenter(this);
    }

    @Override
    protected void initView() {
        dp40 = ScreenUtils.convertDpToPixel(40, this);
        dp84 = ScreenUtils.convertDpToPixel(65, this);
        dp160 = ScreenUtils.convertDpToPixel(120, this);
        dp100 = ScreenUtils.convertDpToPixel(180, this);

        ViewGroup.MarginLayoutParams tvYouAreHereLayoutParams = (ViewGroup.MarginLayoutParams) tvYouAreHere.getLayoutParams();
        tvYouAreHereLayoutParams.bottomMargin = (int) (screenHeight * 0.05);

        ViewGroup.MarginLayoutParams tvChooseSexParams = (ViewGroup.MarginLayoutParams) tvChooseSex.getLayoutParams();
        tvChooseSexParams.bottomMargin = (int) (screenHeight * 0.1);
        ViewGroup.MarginLayoutParams tvSurpriseParams = (ViewGroup.MarginLayoutParams) tvSurprise.getLayoutParams();
        tvSurpriseParams.topMargin = (int) (screenHeight * 0.1);

        llBoyAndGirl.post(() -> {
            try {
                ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) llRecyclerContainer.getLayoutParams();
                layoutParams.topMargin = llBoyAndGirl.getBottom();
                llRecyclerContainer.setLayoutParams(layoutParams);
            } catch (Exception e) {
                Log.i(TAG, "initView: " + e.getMessage());
            }
        });

        tvSkip.setOnClickListener(this);
        llBoyContainer.setOnClickListener(this);
        llGirlContainer.setOnClickListener(this);
        tvDetermine.setOnClickListener(this);
        tvClear.setOnClickListener(this);
        tvClear.setClickable(false);
        tvDetermine.setClickable(false);
        mAdapter = new ChooseBooksAdapter();
        recyclerView.setAdapter(mAdapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.right = 8;
                outRect.left = 8;
                if (parent.getChildLayoutPosition(view) >= 4) {
                    outRect.top = 16;
                }
            }
        });
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_choose_sex;
    }

    @Override
    public void retryRefreshData() {

    }

    private boolean isChosen = false;

    @Override
    public void onClick(View v) {
        /**
         * 跳过
         */
        if (v == tvSkip) {
            PreferenceUtil.getInstance(this).saveUserGender(Integer.valueOf("3"));
            mPresenter.skipChoose("3", "");
//            mPresenter.loadBooks(mGender, mAdapter.getChosenItems());
            if (isAddBook) {
                MainActivity.start(this);
                finish();
            } else {
                String chosenItems = mAdapter.getChosenItems();
                if (!TextUtils.isEmpty(chosenItems)) {
                    GiftBooksActivity.start(this, mGender, mAdapter.getChosenItems());
                } else {
                    GiftBooksActivity.start(this);
                }
                finish();
            }
        }
        /**
         * 选择男
         */
        if (v == llBoyContainer) {
            if (isNetwork()) {
                if (!isChosen) {
                    showAnim();
                }
                chooseBoy();
            }
        }
        /**
         * 选择女
         */
        if (v == llGirlContainer) {
            if (isNetwork()) {
                if (!isChosen) {
                    showAnim();
                }
                chooseGirl();
            }

        }
        /**
         *
         */
        if (v == tvDetermine) {
//            mPresenter.loadBooks(mGender, mAdapter.getChosenItems());
            if (isNetwork()) {
                if (isAddBook) {
                    MainActivity.start(this);
                    finish();
                } else {
                    String chosenItems = mAdapter.getChosenItems();
                    if (!TextUtils.isEmpty(chosenItems)) {
                        GiftBooksActivity.start(this, mGender, mAdapter.getChosenItems());
                    } else {
                        GiftBooksActivity.start(this);
                    }
                    finish();
                }
            }
        }
        if (v == tvClear) {
            if (isNetwork()) {
                mAdapter.clearSelected();
            }
        }
    }

    private void showAnim() {
        ObjectAnimator tvYouAreHereAnimator = ObjectAnimator.ofFloat(tvYouAreHere, "translationY", 0, -dp40);
        ObjectAnimator tvChooseSexAnimator = ObjectAnimator.ofFloat(tvChooseSex, "translationY", 0, -dp84);
        ObjectAnimator llBoyAndGirlAnimator = ObjectAnimator.ofFloat(llBoyAndGirl, "translationY", 0, -dp160);
        ObjectAnimator tvSurpriseAnimator = ObjectAnimator.ofFloat(tvSurprise, "translationY", 0, -dp100);
        ObjectAnimator llRecyclerContainerAnimator = ObjectAnimator.ofFloat(llRecyclerContainer, "translationY", 0, -dp160);
        ObjectAnimator llRecyclerAnimator = ObjectAnimator.ofFloat(llRecyclerContainer, "alpha", 0, 1);

        llRecyclerAnimator.setStartDelay(400);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(tvYouAreHereAnimator, tvChooseSexAnimator,
                llRecyclerContainerAnimator,
                llRecyclerAnimator,
                llBoyAndGirlAnimator, tvSurpriseAnimator);
        animatorSet.setDuration(1000);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.addListener(new SimpleAnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (tvClear != null)
                    tvClear.setClickable(true);

                if (tvDetermine != null)
                    tvDetermine.setClickable(true);
            }
        });
        animatorSet.start();
        isChosen = true;
    }

    private void chooseBoy() {
        if (mGender != null && mGender.equals("1")) {
            return;
        }
        mGender = "1";
        mPresenter.loadCategories("1");
        PreferenceUtil.getInstance(this).saveUserGender(Integer.valueOf("1"));
        ivBoy.setImageResource(R.mipmap.boy_selected);
        ivGirl.setImageResource(R.mipmap.girl);
        tvBoy.setTextColor(0xFF333333);
        tvGirl.setTextColor(0xFF999999);
    }

    //        llGirlContainer.setClickable(false);
//        llBoyContainer.setClickable(false);
    private void chooseGirl() {
        if (mGender != null && mGender.equals("2")) {
            return;
        }
        mGender = "2";
        mPresenter.loadCategories("2");
        PreferenceUtil.getInstance(this).saveUserGender(Integer.valueOf("2"));
        ivGirl.setImageResource(R.mipmap.girl_selected);
        ivBoy.setImageResource(R.mipmap.boy);
        tvGirl.setTextColor(0xFF333333);
        tvBoy.setTextColor(0xFF999999);
    }

    @Override
    public void initData() {
        if (mPresenter == null) {
            initPresenter();
        }
        mPresenter.touristLogin(DeviceUtils.getIMEI(ReSouApplication.getRSApplication()) + "游客");
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {
        ToastUtil.makeLongToast("网络异常");
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void setCategories(List<GenderCategory> categories) {
        mAdapter.setCategories(categories);
        mPresenter.loadBooks(mGender, mAdapter.getChosenItems());
    }

    @Override
    public void noAddBook() {
        Log.i(TAG, "noAddBook: 暂未添加五本书");
        recyclerView.setVisibility(View.VISIBLE);
        isAddBook = false;
    }

    @Override
    public void addBook() {
        Log.i(TAG, "noAddBook: 已经添加五本书");
        recyclerView.setVisibility(View.INVISIBLE);
        tvClear.setVisibility(View.INVISIBLE);
        tvSurprise.setVisibility(View.INVISIBLE);
        tvINfo.setVisibility(View.INVISIBLE);
        isAddBook = true;
    }

}
